package egovframework.npqs.pqi.mobile.activity.approve;

import java.util.ArrayList;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.sds.BizAppLauncher.gov.aidl.GovController.IGovCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.activity.LoginActivity;
import egovframework.npqs.pqi.mobile.activity.quarantineresult.QuarantineResultDetail;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.QuarantineResultDetailItem;
import egovframework.npqs.pqi.mobile.jsoncontent.listitem.QuarantineDetailListItem;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineRequestUpdateThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineStatusDetailThread;
import egovframework.npqs.pqi.mobile.jsonparser.QuarantineStatusDetailThread.QuarantineStatusDetailThreadCallback;

//결재관리상세
public class ApproveListDetail extends Activity implements OnClickListener
	, OnItemSelectedListener, QuarantineStatusDetailThreadCallback{
	private TextView titleTxt;	// 상단 타이틀
	private AppStatus myapp;
	private Context context;
	private String recNo;
	
	private ImageButton upBtn, downBtn, searchBtn, btnHome, btn_back;
	
	private EditText offCdEdit, requestNumEdit, content_1_2;	// 검역신청검역지 코드 에디트 박스, 검역신청 상세번호 에디트 박스
	
	private ListView listView;
	private QuarantineStatusDetailListAdapter quarantineDetailListAdapter;
	
	private TextView headerTotTxt, content11_1, text_hwa_no, text_bl_no, navigation, trnNm;
	private TextView content2_1, content2_2, content3_1, content4_1, content4_2;
	private TextView content5_1, content7_1, content7_2, photo_name, content10_1, content9_1, content8_1;
	
	private ImageButton button3_1, button10_1;
	private TextView button6_1, button6_2, button6_3;
	private EditText content10_2, content12_1;
	private RelativeLayout detail_layout6;
	
	private QuarantineResultDetailItem quarantineResultItem;
	private QuarantineStatusDetailThread quarantineThread;
	private ArrayList<QuarantineDetailListItem> prodArrList;
	
	//하단 리스트 해더
	private LinearLayout list_header_Layout;
	
	private Button footerBtn01, footerBtn02, footerBtn03, footerBtn04;	// 하단 버튼
	private final static int MSG_QUARANTINE_COMPLETED = 0;
	private final static int MSG_QUARANTINE_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private boolean searchState;
	
	private String mResult;
	
	/* G-MOBILE 변수*/
    private String temp;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AppStatus.navigation.addPathLocation("결재관리상세");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_quarantine_status_detail);
		
		Intent intent = getIntent();
		recNo = intent.getStringExtra("recNo");
		init();
	}
	
	private void init(){
		context = this;
		myapp = (AppStatus) getApplicationContext();
		myapp.startBroker(context);
		
		titleTxt = (TextView)findViewById(R.id.headerTitleText);
		titleTxt.setText("결재관리상세");
		
		navigation = (TextView)findViewById(R.id.navigation);
		navigation.setText(AppStatus.navigation.getPath());
		Log.i("AppStatus.navigation.getPath()->", AppStatus.navigation.getPath());
		
		//하단 리스트 해더
		list_header_Layout = (LinearLayout)findViewById(R.id.list_header_Layout);
		list_header_Layout.setVisibility(View.VISIBLE);
		
		offCdEdit = (EditText)findViewById(R.id.content_1_1);
		offCdEdit.setText(myapp.getLoginItem().getOffCd());
		
		requestNumEdit = (EditText)findViewById(R.id.content_1_2);
		requestNumEdit.setText(recNo);
		
		searchBtn = (ImageButton)findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(this);
		
		/*loginBtn = (ImageButton)findViewById(R.id.btnLogin);
		loginBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.appFinish(ApproveListDetail.this);				
			}
		});*/
		
		btn_back = (ImageButton)findViewById(R.id.btn_back);
		btn_back.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		btnHome = (ImageButton)findViewById(R.id.btnHome);
		btnHome.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myapp.setAbleHome(true);
				myapp.dialog.dismiss();
				finish();
			}
		});
		
		searchState = false;
		listView = (ListView)findViewById(R.id.qua_detail_list);
		quarantineDetailListAdapter = new QuarantineStatusDetailListAdapter();
		
		footerBtn01 = (Button)findViewById(R.id.footer01Btn);
		footerBtn02 = (Button)findViewById(R.id.footer02Btn);
		footerBtn03 = (Button)findViewById(R.id.footer03Btn);
		footerBtn04 = (Button)findViewById(R.id.footer04Btn);
		
		content2_1 = (TextView)findViewById(R.id.content_2_1);
		content2_2 = (TextView)findViewById(R.id.content_2_2);
		content3_1 = (TextView)findViewById(R.id.content_3_1);
		content4_1 = (TextView)findViewById(R.id.content_4_1);
		content4_2 = (TextView)findViewById(R.id.content_4_2);
		content5_1 = (TextView)findViewById(R.id.content_5_1);
		content7_1 = (TextView)findViewById(R.id.content_7_1);
		content7_2 = (TextView)findViewById(R.id.content_7_2);
		content10_1 = (TextView)findViewById(R.id.content_10_1);
		text_hwa_no = (TextView)findViewById(R.id.text_hwa_no);		//화물관리번호
		text_bl_no = (TextView)findViewById(R.id.text_bl_no);		//bl번호
		
		button3_1 = (ImageButton)findViewById(R.id.button_3_1);
		button6_1 = (TextView)findViewById(R.id.button_6_1);
		button6_2 = (TextView)findViewById(R.id.button_6_2);
		button6_3 = (TextView)findViewById(R.id.button_6_3);
		button10_1 = (ImageButton)findViewById(R.id.button_10_1);
		
		content8_1 = (TextView)findViewById(R.id.content_8_1);
		content11_1 = (TextView)findViewById(R.id.content_11_1);
		content9_1 = (TextView)findViewById(R.id.content_9_1);
		content10_2 = (EditText)findViewById(R.id.content_10_2);
		content12_1 = (EditText)findViewById(R.id.content_12_1);
		content_1_2 = (EditText)findViewById(R.id.content_1_2);		//검역신청번호 뒷자리
		trnNm = (TextView)findViewById(R.id.trnNm);		//수출입구분
		
		content12_1.setInputType(InputType.TYPE_NULL);
		content12_1.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Log.i("hasFocus","hasFocus = " + hasFocus);
				myapp.utilm.InputKeybordHidden(context, content12_1);
			}
		});
		
		detail_layout6 = (RelativeLayout)findViewById(R.id.detail_layout6);
		
		//footerBtn01.setOnClickListener(this);
		footerBtn02.setOnClickListener(this);
		footerBtn03.setOnClickListener(this);
		footerBtn04.setOnClickListener(this);
		
		footerBtn01.setBackgroundResource(R.drawable.f_blank_sel);
		footerBtn02.setBackgroundResource(R.drawable.f_blank_sel);
		footerBtn03.setBackgroundResource(R.drawable.foot_approval_selector);
		footerBtn04.setBackgroundResource(R.drawable.f_blank_sel);
		
		myapp.showDialogNo(context);
		temp = "처음검색";
		//asyncTaskIsConnectedVPN();
		threadStart();
		
	}
	
	private void searchDetail(){
		searchState = true;
		myapp.showDialogNo(context);	// 페이지가 로드 될때 다이얼로그 출력.
		temp = "조건검색";
		myapp.utilm.InputKeybordHidden(context, requestNumEdit);
		//asyncTaskIsConnectedVPN();
		threadStart();
	}
	
	public void threadStart(){
		if("조건검색".equals(temp)){
    		quarantineThread = new QuarantineStatusDetailThread(context, this
    				, myapp.getLoginItem().getOffCd()
    				, requestNumEdit.getText().toString()
    				, AppStatus.getmUserId());
    		quarantineThread.start();
    	}
    	if("처음검색".equals(temp)){
    		quarantineThread = new QuarantineStatusDetailThread(context, this
    				, myapp.getLoginItem().getOffCd(), recNo, AppStatus.getmUserId());
    		quarantineThread.start();
    	}
	}
	
	private void layoutSetting() {
		content2_1.setText(quarantineResultItem.getResOffCd() +"-"+quarantineResultItem.getResNo());
		content2_2.setText(quarantineResultItem.getResultProgrsNm());
		content3_1.setText(quarantineResultItem.getVenNm());
		content4_1.setText(quarantineResultItem.getVenRep());
		//연락처
		content4_2.setText(quarantineResultItem.getVenTelNo());
		content4_2.setPaintFlags(content4_2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
		content4_2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri n = Uri.parse("tel: "+content4_2.getText());
				startActivity(new Intent(Intent.ACTION_DIAL, n));
			}
		});
		content5_1.setText(quarantineResultItem.getNatNm());
		content7_1.setText(quarantineResultItem.getDelayNm());
		content7_2.setText(quarantineResultItem.getDelayRcognAt());
		content8_1.setText(quarantineResultItem.getValidflagNm());
		content9_1.setText(quarantineResultItem.getInsPlace());
		content10_1.setText(quarantineResultItem.getQuranNm1()+ "  "+quarantineResultItem.getQuranNm2());
		content11_1.setText(quarantineResultItem.getPassResrveReasonNm());
		content12_1.setText(quarantineResultItem.getRemark());
		text_hwa_no.setText(quarantineResultItem.getHwaNo());
		text_bl_no.setText(quarantineResultItem.getBlNo());
		trnNm.setText(quarantineResultItem.getTrnNm());
		
		if(quarantineResultItem.getPzsCnt().equals("0")){	// 과태료 여부 안보이게
			button3_1.setVisibility(View.GONE);
		}
		
		if(quarantineResultItem.getPenCnt().equals("0")){	// 긴급제한 여부 안보이게
			button6_1.setVisibility(View.GONE);
		}
		
		if(quarantineResultItem.getExpCnt().equals("0")){	// 수입금지 안보이게
			button6_2.setVisibility(View.GONE);
		}
		
		if(quarantineResultItem.getDbyhsCnt().equals("0")){	// 관련병해충 안보이게
			button6_3.setVisibility(View.GONE);
		}
		
		if(quarantineResultItem.getPenCnt().equals("0") &&
				quarantineResultItem.getExpCnt().equals("0") &&
				quarantineResultItem.getDbyhsCnt().equals("0")){	// 한줄 없애기
			detail_layout6.setVisibility(View.GONE);
		}
		
		prodArrList = quarantineResultItem.getItems();
		
		headerTotTxt = (TextView)findViewById(R.id.header_tot);
		upBtn = (ImageButton)findViewById(R.id.header_up_btn);
		downBtn = (ImageButton)findViewById(R.id.header_down_btn);

		headerTotTxt.setText("총 품목:"+quarantineResultItem.getItemsResult()+"건");
		listView.setAdapter(quarantineDetailListAdapter);
		
		upBtn.setOnClickListener(this);
		downBtn.setOnClickListener(this);
		downBtn.performClick();
		
	}
	
	@Override
	public void onClick(View v) {
		Intent intent ;
		switch (v.getId()) {
		
		case R.id.search_btn:
			if(content_1_2.getText().toString().length()==8){
				searchDetail();
			}else{
				myapp.utilm.ShowDialog(ApproveListDetail.this, "실패", "검역신청 번호 뒤 8자리를 입력해 주세요.", 20);
			}
			break;
		
		case R.id.footer01Btn:	// 목록 버튼
			onBackPressed();
			break;
			
		case R.id.footer03Btn:	// 결재 버튼
			intent = new Intent(ApproveListDetail.this, ApproveDetail.class);
			intent.putExtra("resNo", quarantineResultItem.getResNo());
			intent.putExtra("resOffCd", quarantineResultItem.getResOffCd());
			intent.putExtra("value", "0");
			startActivity(intent);
			break;
			
		case R.id.header_up_btn:
			RelativeLayout.LayoutParams listParams = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 400));
			listParams.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams);
			break;
			
		case R.id.header_down_btn:
			RelativeLayout.LayoutParams listParams1 = new RelativeLayout.LayoutParams
		    (LayoutParams.WRAP_CONTENT, myapp.utilm.getDpToPixel(context, 53));
			listParams1.addRule(RelativeLayout.ABOVE, R.id.bottom_layout);
			listView.setLayoutParams(listParams1);
			break;			

		default:
			break;
		}
		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_QUARANTINE_COMPLETED:
				layoutSetting();
				break;

			case MSG_QUARANTINE_ERROR:
				String errMsg = "";
				if(msg == null ||msg.obj.toString().equals("")){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				myapp.utilm.ShowDialog(ApproveListDetail.this, "실패", errMsg, 20);
				
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(ApproveListDetail.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};
	
	class QuarantineStatusDetailListAdapter extends BaseAdapter {
		TextView detail_list_seq, detail_list_trfclsf_cd, detail_list_item_type, detail_list_hs_cd;
		TextView detail_list_itm_qty, detail_list_prod_name, detail_list_ins_qty;
		
		@Override
		public int getCount() {
			return prodArrList.size();
		}

		@Override
		public Object getItem(int position) {
			return prodArrList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			//if (convertView == null || convertView != null) {
    			LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			convertView = inflater.inflate(R.layout.list_status_detail_item, parent, false);
    		//}
			
			
			detail_list_seq = (TextView)convertView.findViewById(R.id.detail_list_seq);
			detail_list_trfclsf_cd = (TextView)convertView.findViewById(R.id.detail_list_trfclsf_cd);
			detail_list_itm_qty = (TextView)convertView.findViewById(R.id.detail_list_itm_qty);
			detail_list_prod_name = (TextView)convertView.findViewById(R.id.detail_list_prod_name);
			detail_list_item_type = (TextView)convertView.findViewById(R.id.detail_list_item_type);
			detail_list_ins_qty = (TextView)convertView.findViewById(R.id.detail_list_ins_qty);
			detail_list_hs_cd = (TextView)convertView.findViewById(R.id.detail_list_hs_cd);
			
			detail_list_seq.setText(prodArrList.get(position).getRecSeq());
			detail_list_trfclsf_cd.setText(prodArrList.get(position).getPrdlstCode());
			detail_list_itm_qty.setText(prodArrList.get(position).getItmQty());
			detail_list_prod_name.setText(prodArrList.get(position).getPrdlstNm());
			detail_list_ins_qty.setText(prodArrList.get(position).getInsQty());
			detail_list_item_type.setText(prodArrList.get(position).getItemType());
			detail_list_hs_cd.setText(prodArrList.get(position).getHsCd());
			
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					listItemClickEvent(position);
				}
			});
			
			return convertView;
		}
		
		private void listItemClickEvent(final int position) {
			myapp.utilm.showToast(context, position+"번째 클릭");
		}
	}
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {}

	@Override
	public void OnQuarantineStatusDetailCompleted(boolean isNetworkConntected,
			QuarantineResultDetailItem quarantineItem, String message) {
		
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(quarantineItem != null) {
			this.quarantineResultItem = quarantineItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_QUARANTINE_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	@Override
	public void OnQuarantineStatusDetailError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_QUARANTINE_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(myapp.isFinishState()||myapp.isAbleHome()){
			finish();
		}
		if(myapp.isDataDetailLoadState()){
			myapp.startBroker(context);
			layoutSetting();
			myapp.setDataDetailLoadState(false);
		}
	}
	/*
	@Override
	protected void onRestart() {
		searchBtn.performClick();
		super.onRestart();
	}*/
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		AppStatus.navigation.delPathLocation();
	}

	private void reesultToast() {
		runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(context, mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }
	
}